package com.pm.web.controller.buglist;


import com.alibaba.fastjson2.JSONObject;
import com.pm.buglist.domain.Bugs;
import com.pm.buglist.domain.GYSBugs;
import com.pm.buglist.domain.vo.ImportBug;
import com.pm.buglist.domain.vo.OaWaiveParam;
import com.pm.buglist.domain.vo.ProjectBugVo;
import com.pm.buglist.service.BugsService;
import com.pm.buglist.service.SysFilesService;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.page.TableDataInfo;
import com.pm.common.enums.BusinessType;
import com.pm.common.enums.FileType;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.poi.ExcelUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 项目bugs列表 前端控制器
 * </p>
 *
 * @author wwm
 * @since 2023-12-14
 */
@RestController
@RequestMapping("/business/bugs")
public class BugsController extends BaseController {

    @Resource
    private BugsService bugsService;

    @Resource
    private SysFilesService sysFilesService;

    /**
     * 查询项目bugs列列表
     */
//    @PreAuthorize("@ss.hasPermi('business:bugs:list')")
    @GetMapping("/list")
    public TableDataInfo list(Bugs bugs)
    {
        startPage();
        List<Bugs> list = bugsService.selectBugsList(bugs);
        return getDataTable(list);
    }


    @GetMapping("/wbgys")
    public TableDataInfo wbgys(Bugs bugs)
    {
        startPage();
        List<GYSBugs> list = bugsService.assignGYSBugsList(bugs);
        return getDataTable(list);
    }

    /**
     * 获取项目bugs列详细信息
     */
//    @PreAuthorize("@ss.hasPermi('business:bugs:query')")
    @GetMapping("/getBugsDetail/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Bugs bugs = bugsService.selectBugsById(id);
        return AjaxResult.success(bugs);
    }

    /**
     * 新增项目bugs列
     */
    @PreAuthorize("@ss.hasPermi('business:bugs:add')")
    @Log(title = "项目bugs列:新增", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Bugs bugs)
    {
        return toAjax(bugsService.insertBugs(bugs));
    }

    /**
     * 修改项目bugs列
     */
    @PreAuthorize("@ss.hasPermi('business:bugs:edit')")
    @Log(title = "项目bugs列", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult edit(@RequestBody Bugs bugs)
    {
        return bugsService.updateBugs(bugs);
    }

    @PreAuthorize("@ss.hasPermi('business:bugs:close')")
    @Log(title = "项目bugs列:关闭bugs",businessType = BusinessType.UPDATE)
    @PostMapping("/close")
    public AjaxResult closeBugs(@RequestBody Bugs bugs){
        return bugsService.closeBugsById(bugs);
    }

    @PreAuthorize("@ss.hasPermi('business:bugs:waive')")
    @Log(title = "项目bugs列:废弃bugs",businessType = BusinessType.UPDATE)
    @PostMapping("/waive")
    public AjaxResult waiveBugs(@RequestBody Bugs bugs){
        //bug可以由bug创建人或者dqa废弃
        return bugsService.waiveBugsById(bugs);
    }

    @PreAuthorize("@ss.hasPermi('business:bugs:handle')")
    @Log(title = "项目bugs列:bugs处理",businessType = BusinessType.UPDATE)
    @PostMapping("/handle")
    public AjaxResult bugsHandle(@RequestBody Bugs bugs){
        return bugsService.handleProjectBug(bugs);
    }

    @PreAuthorize("@ss.hasPermi('business:bugs:transfer')")
    @Log(title = "项目bugs列:bug转办",businessType = BusinessType.UPDATE)
    @PostMapping("/transfer")
    public AjaxResult BugTransfer(@RequestBody Bugs bugs){
        return bugsService.transferBug(bugs);
    }

    @GetMapping("/getHandleHistory/{id}")
    public  AjaxResult getBugHandleList(@PathVariable("id")Long id){
        return bugsService.bugHandleLogList(id);
    }

    @GetMapping("/projectBugsList")
    public TableDataInfo getProjectBugsList(ProjectBugVo projectBugVo){
        startPage();
        List<ProjectBugVo> projectBugVos = bugsService.projectBugsList(projectBugVo);
        return getDataTable(projectBugVos);
    }

    /**
     * 导出项目bugs列列表
     */
    @PreAuthorize("@ss.hasPermi('business:bugs:export')")
    @Log(title = "项目bugs列:bug库导出（所有的描述与分析与对策）", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProjectBugVo bugs) throws Exception {
        List<ProjectBugVo> list = bugsService.projectBugsList(bugs);
        ExcelUtil<ProjectBugVo> util = new ExcelUtil<ProjectBugVo>(ProjectBugVo.class);
        util.exportExcel(response, list, "项目bugs列数据");
    }

    /**
     * 导出项目bugs列表
     */
    @PreAuthorize("@ss.hasPermi('business:bugs:export')")
    @Log(title = "项目bugs列:导出第一版本的描述，最后关闭版本的分析与对策", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTwo")
    public void exportTwo(HttpServletResponse response, ProjectBugVo bugs)
    {
        List<ProjectBugVo> list = bugsService.projectBugsListTwo(bugs);
        ExcelUtil<ProjectBugVo> util = new ExcelUtil<ProjectBugVo>(ProjectBugVo.class);
        util.exportExcel(response, list, "项目bugs列数据");
    }

    @PreAuthorize("@ss.hasPermi('business:bugs:remove')")
    @Log(title = "项目bugs列:删除bug", businessType = BusinessType.DELETE)
    @GetMapping("/delete/{id}")
    public AjaxResult deleteBug(@PathVariable("id")Long id){
        return bugsService.delBugById(id);
    }

    @PreAuthorize("@ss.hasPermi('business:bugs:reset')")
    @Log(title = "项目bugs列:重置waive状态Bug", businessType = BusinessType.UPDATE)
    @GetMapping("/reset/{id}")
    public AjaxResult resetBug(@PathVariable("id")Long id){
        return bugsService.resetBugById(id);
    }


    @PreAuthorize("@ss.hasPermi('business:bugs:activation')")
    @Log(title = "项目bugs列:激活关闭的bug", businessType = BusinessType.UPDATE)
    @GetMapping("/activation/{id}")
    public AjaxResult activationBug(@PathVariable("id")Long id){
        return bugsService.activationBugById(id);
    }

    @PreAuthorize("@ss.hasPermi('business:bugs:pjBugImport')")
    @Log(title = "项目bugs列:导入对应项目的bug", businessType = BusinessType.INSERT)
    @PostMapping("/import")
    public AjaxResult importProjectBug(@RequestParam("file") MultipartFile file, @RequestParam("pid")Long pid) throws IOException {
        if(ObjectUtils.isEmpty(pid)){
            return AjaxResult.error("项目id不能为空");
        }
        //获取到导入的数据
        ExcelUtil<ImportBug> excelUtil = new ExcelUtil<ImportBug>(ImportBug.class);
        List<ImportBug> bugList = excelUtil.importExcel(file.getInputStream());
        AjaxResult ajaxResult = bugsService.batchImportBugs(bugList, pid);
        Long userId = SecurityUtils.getUserId();
        if(ajaxResult.isSuccess()){
            //导入成功保存导入的excel数据
            new Thread(()->{
                sysFilesService.FileUploadTwo(file, FileType.IMPORT.getCode(),userId,"批量导入项目下的bug");
            }).start();
        }
        return ajaxResult;
    }

    /**
     * 查询首页测试统计数据
      * @param bug
     * @return
     */
    @GetMapping("/handleBugCount")
    public AjaxResult getBugsCount(Bugs bug){
        List<List<Object>> lists = bugsService.selectBugsCount(bug);
        return AjaxResult.success(lists);
    }

    /**
     * 获取异常类别统计数据
     * */
    @GetMapping("/getExceptionTypeCount")
    public AjaxResult getExceptionTypeCount(){
        return bugsService.getExceptionTypeDate();
    }

    /**
     * 查询Dqe bug结案数据统计
     * */
    @GetMapping("/closeACaseDateCount")
    public AjaxResult getCloseACaseDateCount(){
        return bugsService.findCloseACaseDateCount();
    }

    /**
     * 查询异常代码数据统计
     * */
    @GetMapping("/getExceptionCodeTypeCount")
    public AjaxResult getExceptionCodeTypeCount(Bugs bugs){
        return bugsService.findExceptionCodeType(bugs);
    }


    /**
     * 供应商导出bugs列表
     */
    @PreAuthorize("@ss.hasPermi('business:bugs:gysExportBugs')")
    @Log(title = "项目bugs列表:bug导出", businessType = BusinessType.EXPORT)
    @PostMapping("/gysExportBugs")
    public void gysExportBugs(HttpServletResponse response, Bugs bugs) throws Exception {

        List<GYSBugs> list = bugsService.assignGYSBugsList(bugs);
        //过滤掉html标签
        list.stream().forEach(item->{
            String bugDescriptions= item.getDescriptions();
            String bugAnalysis = item.getAnalysis();
            String bugAnswer = item.getAnswer();

            if(!StringUtils.isEmpty(bugDescriptions)){
                //获取图片路径
                String src1 = com.pm.common.utils.StringUtils.filterImageSrc(bugDescriptions);
                if(!StringUtils.isEmpty(src1)){
                    if(src1.contains("/upload")){
                        String path = src1.substring(src1.lastIndexOf("/upload"));
                        item.setDImgPath(path);
                    }
                }
                //开始过滤
                String ds = com.pm.common.utils.StringUtils.filterHtmlTags(bugDescriptions).replaceAll(" ","");
                item.setDescriptions(ds);
            }

        });
        ExcelUtil<GYSBugs> util = new ExcelUtil<GYSBugs>(GYSBugs.class);
        util.exportExcel(response, list, "bugs列表数据");
    }




    /**
     * 导出bugs列表
     */
    @PreAuthorize("@ss.hasPermi('business:bugs:exportBugs')")
    @Log(title = "项目bugs列表:bug导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportThree")
    public void exportThree(HttpServletResponse response, Bugs bugs) throws Exception {
        if(!CollectionUtils.isEmpty(bugs.getIds())){//判断是否是勾选数据导出
            bugs.setExportFlag("1");
        }
        List<Bugs> list = bugsService.selectBugsList(bugs);
        //过滤掉html标签
        list.stream().forEach(item->{
            String bugDescriptions= item.getDescriptions();
            String bugAnalysis = item.getAnalysis();
            String bugAnswer = item.getAnswer();

            if(!StringUtils.isEmpty(bugDescriptions)){
                //获取图片路径
                String src1 = com.pm.common.utils.StringUtils.filterImageSrc(bugDescriptions);
                if(!StringUtils.isEmpty(src1)){
                    if(src1.contains("/upload")){
                        String path = src1.substring(src1.lastIndexOf("/upload"));
                        item.setDImgPath(path);
                    }
                }
                //开始过滤
                String ds = com.pm.common.utils.StringUtils.filterHtmlTags(bugDescriptions).replaceAll(" ","");
                item.setDescriptions(ds);
            }

        });
        ExcelUtil<Bugs> util = new ExcelUtil<Bugs>(Bugs.class);
        util.exportExcel(response, list, "bugs列表数据");
    }

    /**
     * DQE获取研发申请废弃的bug数据
     * */
    @GetMapping("/getApproveWaiveBugs")
    public TableDataInfo getApproveWaiveBugs(Bugs bugs){
        startPage();
        List<Bugs> approveWaiveBug = bugsService.findApproveWaiveBug();
        return getDataTable(approveWaiveBug);
    }

    /**
     * 获取申请waive/waive的bug数据
     * */
    @GetMapping("/getWaiveRecordBugs")
    public TableDataInfo getWaiveRecordBugs(Bugs bugs){
        startPage();
        List<Bugs> waiveRecordBug = bugsService.findWaiveRecord(bugs.getPid(),bugs.getPutOATab());
        return getDataTable(waiveRecordBug);
    }

    /**
     * 推送oa系统waive申请流程接口
     * @param oaWaiveParam
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:waiveBugs:putOA')")
    @PostMapping("/putOaWaive")
    public AjaxResult putOaWaive(@RequestBody OaWaiveParam oaWaiveParam){
        return bugsService.putBugsToOaWaive(oaWaiveParam);
    }

    /**
     * 根据项目编码查询汇总项目BUG数据
     * @param param
     * @return
     */
    @PostMapping("/queryTotalBugByProject")
    public AjaxResult queryTotalBugByProject(@RequestBody JSONObject param){
        return bugsService.queryTotalBugByProject(param);
    }

    /**
     * 根据项目编码查询汇总项目BUG类型数据
     * @param param
     * @return
     */
    @PostMapping("/queryTotalBugTypeByProject")
    public AjaxResult queryTotalBugTypeByProject(@RequestBody JSONObject param){
        return bugsService.queryTotalBugTypeByProject(param);
    }

}

